package com.lp.controller.iot;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lp.bo.IotNodeInfoBO;
import com.lp.bo.IotSensorDeviceInfoBO;
import com.lp.bo.IotSensorInfoBO;
import com.lp.bo.IotTriggerInfoBO;
import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.common.Constants;

import com.lp.common.Code;
import com.lp.common.CodeIot;
import com.lp.common.RequestURLIOT;
import com.lp.controller.BaseController;
import com.lp.util.ObjectUtil;
import com.lp.util.ResultMapUtils;

@Controller

public class IotSensorDeviceInfoController extends BaseController {
	/**
	 * 检索
	 */
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO_PAGE)
	public ModelAndView selectPage(HttpServletResponse response,
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey,
			@RequestBody IotSensorDeviceInfoBO obj, @RequestParam(required = false) Integer pageSize,
			@RequestParam Integer paged) {
		Map<String, Object> resultMap = getResultMap();
		try {
			resultMap = service.selectPageList("IotSensorDeviceInfo.selectPage", getPageBean(paged, pageSize), obj);
		} catch (Exception e) {
			exception(e, resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}

	/**
	 * 插入
	 */
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO)
	public ModelAndView save(HttpServletResponse response,
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey,
			@RequestBody IotSensorDeviceInfoBO obj) {
		Map<String, Object> resultMap = getResultMap();
		try {
			resultMap = service.insert("IotSensorDeviceInfo.insert", obj);
		} catch (Exception e) {
			exception(e, resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO_COPY)
	public ModelAndView saveCopy(HttpServletResponse response,
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey,
			@RequestBody IotSensorDeviceInfoBO obj) {
		Map<String, Object> resultMap = getResultMap();
		try {
			IotSensorDeviceInfoBO iotSensorDevice = new IotSensorDeviceInfoBO() ;
			iotSensorDevice.setName( obj.getName() );
			iotSensorDevice.setNode_id(obj.getNode_id());
			iotSensorDevice.setAddress(obj.getAddress());
			resultMap = service.insert("IotSensorDeviceInfo.insert", iotSensorDevice);
			
			if(isOk(resultMap)){
				// 插入传感器
				IotSensorInfoBO sensorBo = new IotSensorInfoBO();
				sensorBo.setNode_id(obj.getNode_id());
//				sensorBo.setSensor_device_id(obj.getSensor_device_id()+"");
				sensorBo.setData_type(-1);
				List<IotSensorInfoBO> sensorList =  getData(service.selectList("IotSensorInfo.select", sensorBo));
				if(ObjectUtil.isNotEmpty(sensorList)){
					for(int i=0;i< sensorList.size() ; i++ ){
						// 之前的sensorid
						int sensorId = sensorList.get(i).getId() ;
						//
						IotSensorInfoBO sensor = sensorList.get(i) ;
						sensor.setNode_id(obj.getNode_id());
						sensor.setSensor_device_id(obj.getAddress() );
						sensor.setSdata(0f);
						sensor.setStr_sdata("");
						sensor.setSeq(i);
						sensor.setDelete_flag(0);
						sensor.setIot_sensor_status(17);
						sensor.setRequest_sdata(0f);
						sensor.setRegister_time(new Date());
						sensor.setMtime(new Date());
						sensor.setId(null);
						
						service.insert("IotSensorInfo.insert", sensor) ;
						
						ProCacheUtil.addCache(CacheName.SENSORINFO, sensor.getId().toString(), sensor);
						ProCacheUtil.addCache(CacheName.SENSORINFO_NSP, sensor.getNode_id()+"-"+
											sensor.getSensor_device_id()+"-"+sensor.getPort_id(), sensor);
						
						
						// 添加触发器
						IotTriggerInfoBO trigger = new IotTriggerInfoBO() ;
						trigger.setNode_id(obj.getNode_id());
						trigger.setFrom_sensor_id( sensorId );
						List<IotTriggerInfoBO> triggerList = getData( service.selectList("IotTriggerInfo.select", trigger)) ;
						for(int j=0; j<triggerList.size() ; j++ ){
							IotTriggerInfoBO triggerBo = new IotTriggerInfoBO() ;
							triggerBo.setName( triggerList.get(j).getName() );
							triggerBo.setFrom_sensor_id( sensor.getId() );
							triggerBo.setNode_id( obj.getNode_id() );
							triggerBo.setIot_trigger_condition_type(triggerList.get(j).getIot_trigger_condition_type());
							triggerBo.setIot_trigger_action_type( triggerList.get(j).getIot_trigger_action_type() );
							triggerBo.setAction_params(triggerList.get(j).getAction_params()  );
							triggerBo.setSeq(triggerList.get(j).getSeq());
							triggerBo.setDelete_flag(triggerList.get(j).getDelete_flag());
							triggerBo.setCondition_params(triggerList.get(j).getCondition_params());
							triggerBo.setIot_trigger_alarm_level(triggerList.get(j).getIot_trigger_alarm_level());
							triggerBo.setIot_trigger_alarm_flag(triggerList.get(j).getIot_trigger_alarm_flag());
							// 触发器默认是暂停
							triggerBo.setIot_trigger_status( CodeIot.IOT_TRIGGER_STATUS.STOP );
							triggerBo.setTrigger_inteval_time(triggerList.get(j).getTrigger_inteval_time());
							triggerBo.setLast_trigger_time(triggerList.get(j).getLast_trigger_time());
							triggerBo.setRecovery( triggerList.get(j).getRecovery() );
							
							service.insert("IotTriggerInfo.insert", triggerBo) ;
							// 更新触发器缓存
							List<IotSensorInfoBO> list = getData( service.selectList("IotSensorInfo.selectSensorTriggerList", new IotSensorInfoBO(sensor.getId())) );
							
							if( ObjectUtil.isNotEmpty(list) ){
								ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, sensor.getNode_id()+"-"+ 
										sensor.getSensor_device_id()+"-"+sensor.getPort_id(),  list.get(0));
							}
							
						}
					}
				}
			}
		} catch (Exception e) {
			exception(e, resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}

	/**
	 * 查询单个
	 */
	@RequestMapping(method = RequestMethod.GET, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO)
	public ModelAndView selectOne(HttpServletResponse response, @RequestParam Integer id) {
		Map<String, Object> resultMap = getResultMap();
		try {
			resultMap = service.selectOne("IotSensorDeviceInfo.selectOne", new IotSensorDeviceInfoBO(id));
		} catch (Exception e) {
			exception(e, resultMap, id);
		}
		return getModelAndView(response, resultMap);
	}

	/**
	 * 更新
	 */
	@RequestMapping(method = RequestMethod.PUT, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO)
	public ModelAndView update(HttpServletResponse response, @RequestBody IotSensorDeviceInfoBO obj) {
		Map<String, Object> resultMap = getResultMap();
		try {
			resultMap = service.update("IotSensorDeviceInfo.update", obj);
		} catch (Exception e) {
			exception(e, resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}

	/**
	 * 删除
	 */
	@RequestMapping(method = RequestMethod.DELETE, value = RequestURLIOT.SensorDeviceInfo.SENSOR_DEVICE_INFO)
	public ModelAndView delete(HttpServletResponse response, @RequestParam Integer id) {
		Map<String, Object> resultMap = getResultMap();
		try {
			IotSensorDeviceInfoBO obj = new IotSensorDeviceInfoBO();
			if (ObjectUtil.isEmpty(id)) {
				putStatusCode(resultMap, Code.ResponseCode.SystemCode.PARAM_ERROR);
			} else {
				obj.setId(id);
				// 查询单个
				IotSensorDeviceInfoBO prev = getData( service.selectOne("IotSensorDeviceInfo.selectOne", obj) );
				resultMap = service.delete("IotSensorDeviceInfo.delete", obj);
//				if(isOk(resultMap)){
//					// 这边也删除掉传感器的信息
//					IotSensorInfoBO sensorBo = new IotSensorInfoBO();
//					sensorBo.setNode_id(prev.getNode_id());
//					sensorBo.setSensor_device_id(prev.getAddress());
//					sensorBo.setData_type(-1);
//					List<IotSensorInfoBO> sensorList =  getData(service.selectList("IotSensorInfo.select", sensorBo));
//					if(ObjectUtil.isNotEmpty(sensorList)){
//						for(IotSensorInfoBO tmp : sensorList ){
//							tmp.setDelete_flag(Constants.DELETE.YES);
//							resultMap = service.update("IotSensorInfo.update", tmp) ;		
//							if(isOk(resultMap)){
//								ProCacheUtil.removeCache(CacheName.SENSORINFO, tmp.getId().toString());
//								ProCacheUtil.removeCache(CacheName.SENSORINFO_NSP, tmp.getNode_id()+"-"+tmp.getSensor_device_id()+"-"+tmp.getPort_id());
//							}
//						}
//					}
//				}
			}
		} catch (Exception e) {
			exception(e, resultMap, id);
		}
		return getModelAndView(response, resultMap);
	}
	
	
	/**
	 * 增加从机列表，关联设备和传感器信息
	 */
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.SensorDeviceInfo.DEVICE_INFO_NODE_INFO_SENSOR_INFO_PAGES)
	public ModelAndView selectNodeSensorListPages(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestBody IotSensorInfoBO obj) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO user = getUserInfoByUserKey(userKey);
			obj.setUser_id(user.getId());
			resultMap = service.selectList("IotSensorDeviceInfo.selectSensorDeviceList", obj);
		} catch (Exception e) {
			exception(e,resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}
	
//	/**
//	 * 检索设备信息
//	 * @param response
//	 * @param 
//	 * @return
//	 */
//	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.NodeInfo.NODE_INFO_PAGE_DATA)
//	public ModelAndView selectPage(HttpServletResponse response, 
//			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
//			@RequestBody IotNodeInfoBO obj,
//			@RequestParam(required=false) Integer pageSize ,
//			@RequestParam Integer paged ) {
//		Map<String, Object> resultMap = getResultMap();
//		try {
//			UserInfoBO user = getUserInfoByUserKey(userKey);
//			obj.setUser_id(user.getId());
//			Calendar instance = Calendar.getInstance();
//			instance.add(Calendar.DAY_OF_YEAR, 1);
//			instance.set(Calendar.HOUR_OF_DAY, 0);
//			instance.set(Calendar.MINUTE, 0);
//			instance.set(Calendar.SECOND, 0);
//			Date end_time = instance.getTime();
//			instance.add(Calendar.DAY_OF_YEAR, -1);
//			Date begin_time = instance.getTime();
//			obj.setBegin_time(begin_time);
//			obj.setComplete_time(end_time);
//			resultMap = service.selectPageList("IotNodeInfos.selectDeviceInfoJoinNode",getPageBean(paged,pageSize), obj);	
//		} catch (Exception e) {
//			exception(e,resultMap, obj);
//		}
//		return getModelAndView(response, resultMap);
//	}
	
	/**
	 * 检索传感器信息
	 * @param response
	 * @param 
	 * @return
	 */
//	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.SensorInfo.SENSORS_INFO_PAGE)
//	public ModelAndView selectPage(HttpServletResponse response, 
//			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
//			@RequestBody IotSensorInfoBO obj,
//			@RequestParam(required=false) Integer pageSize ,
//			@RequestParam Integer paged ) {
//		Map<String, Object> resultMap = getResultMap();
//		try {
//			UserInfoBO user = getUserInfoByUserKey(userKey);
//			if( verifyUserRole(user.getUser_key(), Code.UserType.SUPER) && ObjectUtil.isNotEmpty(obj.getNode_id()) ){
//				// 管理员要查看，信息
//				;
//			}else{
//				obj.setUser_id(user.getId());				
//			}
//			resultMap = service.selectPageList("IotSensorInfos.selectPage",getPageBean(paged,pageSize), obj);															
//		} catch (Exception e) {
//			exception(e,resultMap, obj);
//		}
//		return getModelAndView(response, resultMap);
//	}
}
